package cl.scene.libbencode;

import java.io.IOException;
import java.io.InputStream;

/**
 * Created by IntelliJ IDEA.
 * User: Patricio
 * Date: 23-11-2010
 * Time: 11:03:51 PM
 */
public class BencodeParser {
    public static final int READING_LENGHT = 0;
    public static final int READING_STRING_VALUE = 1;
    public static final int READING_INTEGER_VALUE = 2;
    public static final int READING_SIGN = 3;

    public IContainerType parse(InputStream is) throws IOException {
        ListType l = new ListType();
        parse(is, l, false);
        return l;
    }

    public void parse(InputStream is, IContainerType container, boolean readingContainer) throws IOException {
        byte b[] = new byte[1];
        while (is.read(b) > 0) {
            if (b[0] > 47 && b[0] < 59) {
                container.push(new ByteStringValue(is, b));
            } else if (b[0] == 'i') {
                container.push(new IntegerValue(is));
            } else if (b[0] == 'd') {
                System.out.println("D -> ");
                DictionaryType d = new DictionaryType();
                parse(is, d, true);
                container.push(d);
                readingContainer = true;
            } else if (b[0] == 'l') {
                System.out.println("L -> ");
                ListType l = new ListType();
                parse(is, l, true);
                container.push(l);
                readingContainer = true;
            } else if (b[0] == 'e' && readingContainer) {
                return;
            } else {
                throw new IOException("Malformed Stream!");
            }
        }
    }
}
